Ext.ns('App.module.Page');
App.module.Page.Delete = Ext.extend(Ext.util.Observable, {
	constructor: function(config){
		App.module.Page.Add.superclass.constructor.call(this);	
	}
	,init: function(grid){
		this.grid = grid;
		grid.on('render', function(grid){
			var bt = new Ext.Button({
				tooltip: 'Delete'
				,iconCls: 'icon-delete-16x16'
				,disabled: true
				,handler: this.toTrash
				,scope: this
			}, this);
			grid.getTopToolbar().add(bt);
			grid.selModel.on('selectionchange', function(sm){
				bt.setDisabled(!sm.hasSelection());	
			});
		}, this);	
	}
	,toTrash: function(){
		var sm = this.grid.selModel;
		if(!sm.hasSelection()) return;
		
		Ext.Msg.confirm('Delete', 'Do you want to delete?', function(bt){
			if('no' == bt) return;
			
			var view = this.grid.getView();
			var store = this.grid.getStore();
			var records = sm.getSelections();
			var ids = [];
			var rows = [];
			
			for(var i = 0, len = records.length; i < len; i ++){
				ids.push(records[i].data.id);
				rows.push(row = Ext.fly(view.getRow(store.indexOf(records[i]))));
				row.hide(true);
			}
			
			API.page.del({ids: ids}, function(r){
				if(!r) return Ext.Msg.alert('Error', 'Unknow error!');
				if(r.success){
					store.remove(records);
				}else{
					for(var i = 0, len = rows.length; i < len; i ++){
						rows[i].show(true);
					}
					Ext.Msg.alert(r.msg);
				}
			}, this);
		}, this);
	}
});